package com.main.controller;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CreateCache;
import com.main.bo.LoginBO;
import com.main.common.R;
import com.main.mq.MessageRocketmq;
import com.main.pojo.User;
import com.main.service.UserService;
import com.main.util.CaptchaUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 用户相关操作信息类
 *
 * @author RuoYu
 * @date 2022/09/26
 */
@Slf4j
@RequestMapping("user")
@RestController
public class UserController {

    @Autowired
    private CaptchaUtils captchaUtils;

    @Autowired
    private UserService userService;

    @Autowired
    private MessageRocketmq messageRocketmq;

    @CreateCache(area = "sms", name = "user_", expire = 300, timeUnit = TimeUnit.SECONDS)
    private Cache<String, String> jetCache;


    /**
     * 发送短信
     * 发送 验证码 到 电话短信
     *
     * @param user 用户
     * @return {@link R}<{@link String}>
     */
    //    @Cached(area = "sms", name = "user_", key = "#user.phone", expire = 60, cacheType = CacheType.REMOTE)
    @PostMapping("sendSMS")
    @ApiOperation(value = "发送短信")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "用户信息", required = true)
    })
    public R<String> sendSMS(@RequestBody User user) {
        String phone = user.getPhone();
        //1、输入手机号正确
        if (StringUtils.isNoneEmpty(phone)) {
            //2、判断缓存区中有无缓存
            if (!StringUtils.isNoneEmpty(jetCache.get(phone))) {
                String captcha = captchaUtils.getCode(user.getPhone());
                log.info("code:{}", captcha);
//                messageRocketmq.sendMessage(phone, code);//队列发送验证码到邮箱
                jetCache.put(phone, captcha);
                return R.success("短信发送，请留意接收");
            } else {
                return R.success("短信已发送，稍等片刻");
            }
        }
        return R.success("短信发送失败");
    }


    /**
     * 发送 验证码 到 邮件
     *
     * @param user 用户
     * @return {@link R}<{@link String}>
     */
    @PostMapping("sendEmail")
    @ApiOperation(value = "发送 验证码 到 邮件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "用户信息", required = true)
    })
    public R<String> sendEmail(@RequestBody User user) {
        String email = user.getEmail();
        //1、邮箱地址是否存在
        if (StringUtils.isNoneEmpty(email)) {
            //2、缓存区中无缓存
            if (!StringUtils.isNoneEmpty(jetCache.get(email))) {
                String captcha = captchaUtils.getCode(user.getEmail());//生成验证码
                log.info("code:{}", captcha);

                //上线打开！！！！！！！！！
//                messageRocketmq.sendMessage(email, code);//队列发送验证码到邮箱
//                System.out.println(Thread.currentThread().getId() + "--1");
                jetCache.put(email, captcha);//存入缓存
                return R.success("验证码发送成功，请到邮箱进行查收");

            } else {//3、缓存区中有缓存
                return R.success("验证码已发送，稍等片刻");
            }
        }
        return R.error("验证码发送失败");
    }


    /**
     * 登录
     *
     * @param UserLoginInformation 用户登录信息
     * @param request              请求
     * @return {@link R}<{@link User}>
     */
    @PostMapping("login")
    @ApiOperation(value = "登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "UserLoginInformation", value = "用户登录信息", required = true)
    })
    public R<User> login(@RequestBody User UserLoginInformation, HttpServletRequest request) {

        //邮箱快捷登录，没有帐户直接注册登录
        String email = UserLoginInformation.getEmail(), mailCaptcha = UserLoginInformation.getCode();
        log.info("email:{},mailCaptcha:{}", email, mailCaptcha);
        //1、邮箱号码和验证码是否不为空
        if (email != null && mailCaptcha != null) {
//            if (request.getSession().getAttribute("user") != null) {
//                return R.error("该账号已登录");
//            }
            //2、进行登录校验
            LoginBO loginBO = userService.EmailQuickLogin(email, mailCaptcha, request);

            //3、获取返回登录状态
            int code = loginBO.getCode();

            //4、判断是否能登录
            if (code == 1) {//登录成功
                return R.success((User) loginBO.getData());
            } else if (code == 0) {//登录失败
                return R.error(loginBO.getMsg());
            }
        }

        //手机号快捷登录，没有帐户直接注册登录
        String phoneCode = UserLoginInformation.getPhone(), phoneCaptcha = UserLoginInformation.getCode();
        log.info("phoneCode:{},phoneCaptcha:{}", phoneCode, phoneCaptcha);
        //1、手机号码和验证码是否不为空
        if (phoneCode != null && phoneCaptcha != null) {

/*            //2、进行登录校验
            LoginBO loginBO =   userService.PhoneQuickLogin(phoneCode, phoneCaptcha, request);

            //3、获取返回登录状态
            int code = loginBO.getCode();

            //4、判断是否能登录
            if (code == 1) {//登录成功
                return R.success((User) loginBO.getData());
            } else if (code == 0) {//登录失败
                return R.error(loginBO.getMsg());
            }*/
            return R.error("此功能暂未开放");
        }

        //账号登录
        String userName = UserLoginInformation.getUserName(), password = UserLoginInformation.getPassword();
        log.info("userName:{},password:{}", userName, password);
        if ((userName != null && password != null) || (email != null && password != null) || (phoneCode != null && password != null)) {

            //2、进行登录校验
            LoginBO loginBO = userService.accountLogin(UserLoginInformation, password, request);

            //3、返回登录状态
            int code = loginBO.getCode();

            //4、判断是否能登录
            if (code == 1) {//登录成功
                return R.success((User) loginBO.getData());
            } else if (code == 0) {//登录失败
                return R.error(loginBO.getMsg());
            }
        }

        return R.error("系统异常");
    }

    /**
     * 注册
     *
     * @param userInfo 用户信息
     * @return {@link R}<{@link String}>
     */
    @PostMapping("signup")
    public R<String> signup(@RequestBody User userInfo) {
        //用户名
        //密码
        //手机号
        //验证码
        return R.error("");
    }

    /**
     * 退出登录
     *
     * @param request 请求
     * @return {@link R}<{@link String}>
     */
    @PostMapping("logout")
    @ApiOperation(value = "退出登录")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return R.success("退出登录");
    }

    /**
     * 更新用户密码
     *
     * @param user 用户
     * @return {@link R}<{@link String}>
     */
    @PutMapping
    public R<String> updateUserPassword(@RequestBody User user) {
//        boolean b = userService.updateUserPassword(user);
//        log.info("b:{}", b);
        return R.error("信息修改成功");
    }
}
